'''
    Goblinoid: Experience all of MediaGoblin on an Android Device
    Copyright (C) 2015 Dylan Jeffers

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
from __future__ import print_function

from kivy.app import App
from kivy.lang import Builder
from kivy.logger import Logger
from kivy.clock import Clock, mainthread
from kivy.properties import StringProperty, ObjectProperty, BooleanProperty
from kivy.utils import platform

from pypump.exception import PyPumpException
import threading

from goblinoid.root.goblinscreen import GoblinScreen

if platform() == 'android':
    from jnius import cast
    from jnius import autoclass
    from android import activity
    from goblinoid.libs.toast.androidtoast import toast
else:
    from goblinoid.libs.toast.kivytoast import toast

Builder.load_file('goblinoid/media/mediaviews.kv')


if platform() == 'android':
    PythonActivity = autoclass('org.renpy.android.PythonActivity')
    Intent = autoclass('android.content.Intent')
    Uri = autoclass('android.net.Uri')
    MediaStore_Images_Media_DATA = "_data"
    RESULT_LOAD_IMAGE = 1
    Activity = autoclass('android.app.Activity')


def open_image_gallery_activity(callback, on_cancel_callback):

    currentActivity = cast('android.app.Activity', PythonActivity.mActivity)

    def on_activity_result(request_code, result_code, intent):
        if request_code != RESULT_LOAD_IMAGE:
            Logger.warning('ignoring activity result')
            return

        if result_code == Activity.RESULT_CANCELED:
            Logger.warning('RESULT_CANCELLED')
            on_cancel_callback()
            return

        if result_code != Activity.RESULT_OK:
            raise NotImplementedError('UNKNOWN RESULT CODE')

        selectedImage = intent.getData()
        filePathColumn = [MediaStore_Images_Media_DATA]

        cursor = currentActivity.getContentResolver().query(
            selectedImage, filePathColumn, None, None, None)

        cursor.moveToFirst()
        columnIndex = cursor.getColumnIndex(filePathColumn[0])
        picturePath = cursor.getString(columnIndex)
        cursor.close()
        Logger.info('android_ui: user_select_image() selected %s', picturePath)
        Clock.schedule_once(lambda dt: callback(picturePath), 0)

    activity.bind(on_activity_result=on_activity_result)
    intent = Intent()
    intent.setAction(Intent.ACTION_PICK)
    intent.setData(Uri.parse('content://media/internal/images/media'))
    currentActivity.startActivityForResult(intent, RESULT_LOAD_IMAGE)


# TODO: pass a reference to the ActionView instance so we don't have to call
# parent.parent.parent
class UploadView(GoblinScreen):
    upload_image = StringProperty('')
    upload_thread = ObjectProperty()
    cancel = BooleanProperty(False)

    def __init__(self, **kwargs):
        super(UploadView, self).__init__(transition_priority=0, **kwargs)
        if platform == 'android':
            self.init_upload_image()

    def init_upload_image(self):
        open_image_gallery_activity(
            self.set_upload_image, self.cancel_callback)

    def set_upload_image(self, imageUri):
        self.upload_image = imageUri

    def upload_media(self):
        title = self.ids.title.text
        description = self.ids.desc.text
        toast('media uploading...', True)
        self.upload_thread = UploadImage(
            self.upload_image,
            title,
            description,
            self.upload_complete)
        self.upload_thread.start()
        self.cancel_callback()

    def on_upload_thread(self, instance, value):
        print ('upload thread changed state!')

    def cancel_callback(self):
        self.cancel = True

    @mainthread
    def upload_complete(self, image_uri):
        toast('upload complete', True)


class UploadImage(threading.Thread):

    def __init__(self, image_uri, title, description, callback, **kwargs):
        threading.Thread.__init__(self)
        self.image_uri = image_uri
        self.title = title
        self.description = description
        self.callback = callback

    def run(self):
        try:
            pump = App.get_running_app().pump_service.pump
            image = pump.Image(display_name=self.title)
            image.content = self.description
            image.from_file(self.image_uri)
            # callback is causing issues right now, going to forgo for a moment
            # self.callback(self.image_uri)
        except PyPumpException:
            print ('failed to upload image due to PyPumpException')
            pass
        self.is_running = False
